package com.browan.background;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public class Background extends Activity
{
	String TAG = getClass().getSimpleName();
	private GridView gridview;
	private List<BackgroundData> list;

	public static final String URL = "url";
	
	public static final String STYLE = "style";

	private DataManager manager;

	private GridViewAdapter adapter;

	private int postion;

	private int pageIndex;

	private Activity activity;

	private boolean isClickAble;
	
	private int style;

	private DBHelper mDbHelper;
	
	private SQLiteDatabase mDatabase;
	
	
	@Override
	protected void onDestroy()
	{
		mDbHelper.close();
		super.onDestroy();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.main);

		
		
		setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE));
		
		mDbHelper = new DBHelper(this);
		mDatabase = mDbHelper.getDb();

		activity = this;
		manager = DataManager.getInstence();

		style = postion = getIntent().getIntExtra(Welcome.POSTION, 0);

		addListener(findViewById(R.id.pre));
		addListener(findViewById(R.id.next));

		pageIndex = 1;

		gridview = (GridView) findViewById(R.id.gridview);

		gridview.setVerticalFadingEdgeEnabled(true);
		gridview.setVerticalScrollBarEnabled(false);
		gridview.setHorizontalFadingEdgeEnabled(false);
		gridview.setHorizontalScrollBarEnabled(false);

		gridview.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				Intent intent = new Intent(Background.this, Wallpaper.class);
				intent.putExtra(URL, list.get(position).big_url);
				startActivity(intent);
			}
		});

		list = manager.get(postion + "_" + pageIndex);

		if (null == list)
		{
			isClickAble = false;
			list = new ArrayList<BackgroundData>();
			new Thread(loadData).start();
		}
		else
		{
			adapter = new GridViewAdapter(Background.this, list);
			gridview.setAdapter(adapter);
			isClickAble = true;
		}

	}

	private void addListener(View view)
	{

		view.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				if (!isClickAble)
				{
					return;
				}

				switch (v.getId())
				{
				case R.id.pre:// 上一页

					List<BackgroundData> lists = manager.get(postion + "_" + (pageIndex - 1));
					if (null != lists)
					{
						list = lists;
						reloadData();
						pageIndex--;
					}

					break;

				case R.id.next: // 下一页
					List<BackgroundData> lis = manager.get(postion + "_" + (pageIndex + 1));
					if (null != lis)
					{
						list = lis;
						reloadData();
						pageIndex++;
					}
					else
					{
						pageIndex++;
						new Thread(loadData).start();
					}
					break;

				default:
					break;
				}
			}
		});
	}

	private void reloadData()
	{
		adapter = new GridViewAdapter(Background.this, list);
		gridview.setAdapter(adapter);
	}

	Runnable loadData = new Runnable()
	{

		@Override
		public void run()
		{
			isClickAble = false;
			final int index = pageIndex;

			try
			{
				List<BackgroundData> datas = Util.getImages(createUrl(PAGE_SIZE, index));
				isClickAble = true;

				if (null == datas || datas.size() == 0)
				{
					pageIndex--;
					return;
				}
				
				
				
				for (BackgroundData data : datas)
				{
					String bigName = Md5Tool.getMd5Value(data.big_url);

					if (!mDbHelper.isExist(DBHelper.TABLE_NAME, DBHelper.BIG_NAME + " = '" + bigName + "'"))
					{
						String smallName = Md5Tool.getMd5Value(data.little_url);
						ContentValues values = new ContentValues();
						values.put(DBHelper.BIG_NAME, bigName);
						values.put(DBHelper.SMALL_NAME, smallName);
						values.put(DBHelper.BIG_URL, data.big_url);
						values.put(DBHelper.SMALL_URL, data.little_url);
						values.put(DBHelper.STYLE, style);
						mDatabase.insert(DBHelper.TABLE_NAME, null, values);
					}

				}
				
				
				

				list = datas;
				manager.put(postion + "_" + index, datas);
				gridview.post(new Runnable()
				{
					@Override
					public void run()
					{
						reloadData();
					}
				});
			}
			catch (Exception e)
			{
				e.printStackTrace();
				gridview.post(new Runnable()
				{

					@Override
					public void run()
					{

						Builder builder = new AlertDialog.Builder(Background.this);
						builder.setTitle("错误");
						builder.setMessage("数据加载失败！");

						builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
						{

							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								Background.this.finish();
							}
						});
						builder.setPositiveButton("重试", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								new Thread(loadData).start();
							}
						});
						builder.setCancelable(false);
						builder.create().show();
					}
				});
			}
		}
	};

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		if (null == list || 0 == list.size())
		{
		}
		else
		{
			menu.add(0, Menu.FIRST, 0, "浏览模式").setIcon(android.R.drawable.ic_media_play);
		}

		return super.onPrepareOptionsMenu(menu);
	}

	private ArrayList<String> createScanUrl()
	{
		ArrayList<String> arrayList = new ArrayList<String>();
		for (BackgroundData data : list)
		{
			arrayList.add(data.big_url);
		}
		return arrayList;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		boolean ret = true;
		switch (item.getItemId())
		{
		case Menu.FIRST:
			Intent intent = new Intent(this, ScanActivity.class);
//			intent.putStringArrayListExtra(Intent.EXTRA_TEXT, createScanUrl());
			intent.putExtra(Intent.EXTRA_TITLE, createUrl(200, pageIndex));
			intent.putExtra(STYLE, postion);
			startActivity(intent);
			break;
		default:
			ret = super.onOptionsItemSelected(item);
			break;
		}
		return ret;
	}

	// 默认是 16 GTouch 是40
	private static final int PAGE_SIZE = 16;

	// private static final int PAGE_SIZE = 200;

	private String createUrl(int pagesize, int pageIndex)
	{
		return "http://xuan.3g.cn/wallpaperList.aspx?pn=" + pageIndex + "&ps=" + pagesize + "&ftp=" + postion
				+ "&size=85";
	}

	private class GridViewAdapter extends BaseAdapter
	{

		public GridViewAdapter(Context c, List<BackgroundData> list)
		{
			mContext = c;
			urls = list;
			pro = new int[urls.size()];
			isShowProgress = false;
		}

		private Context mContext;
		private List<BackgroundData> urls;

		@Override
		public int getCount()
		{
			return urls.size();
		}

		@Override
		public Object getItem(int position)
		{
			return urls.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		private boolean isShowProgress;

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{

			WebView webView = (WebView) convertView;

			if (null == webView)
			{
				webView = (WebView) LayoutInflater.from(mContext).inflate(R.layout.webview, null);
			}
			webView.setVerticalScrollBarEnabled(false);
			webView.setHorizontalScrollBarEnabled(false);

			webView.getSettings().setJavaScriptEnabled(true);

			webView.getSettings().setBlockNetworkImage(true);

			final int p = position;

			webView.setWebChromeClient(new WebChromeClient()
			{

				public void onProgressChanged(WebView view, int progress)
				{
					// activity.setTitle("Loading...");

					if (isShowProgress)
					{
						return;
					}

					pro[p] = progress * 100;

					activity.setProgress(getcount() / urls.size());

					if (getcount() == 100 * 100 * urls.size())
					{
						isShowProgress = true;
					}
					// activity.setTitle(R.string.app_name);
				}
			});

			webView.loadUrl(urls.get(position).little_url);
			webView.setWebViewClient(client);
			return webView;
		}

		private int[] pro;

		private int getcount()
		{

			int result = 0;
			for (int i = 0; i < pro.length; i++)
			{
				result += pro[i];
			}
			return result;
		}

		WebViewClient client = new WebViewClient()
		{

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon)
			{
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);

			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url)
			{
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url)
			{
				super.onPageFinished(view, url);
				view.setClickable(false);
				view.setFocusable(false);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
			{
				// super.onReceivedError(view, errorCode, description,
				// failingUrl);

				view.loadDataWithBaseURL("about:blank", "载入图片出错！", "text/html", "UTF-8", null);
			}
		};
	}
}